package com.junmoo.www.auth.module.system.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.junmoo.www.auth.module.system.mapper.SysRoleMapper;
import com.junmoo.www.entity.SysRole;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
@AllArgsConstructor
public class SysRoleService {

    private final SysRoleMapper sysRoleMapper;

    public List<SysRole> findAll(){
        return sysRoleMapper.selectList(new QueryWrapper<SysRole>());
    }

    public List<SysRole> findByUserId( Long userId){
        return sysRoleMapper.findByUserId(userId);
    }

    private LambdaQueryWrapper<SysRole> queryByAnd(SysRole entity){
        return new LambdaQueryWrapper<SysRole>()
                .eq(entity.getId()!=null,SysRole::getId,entity.getId())
                .eq( StringUtils.hasText(entity.getRoleName()),SysRole::getRoleName,entity.getRoleName())
                .eq( StringUtils.hasText(entity.getRoleCode()),SysRole::getRoleCode,entity.getRoleCode())
                .eq( StringUtils.hasText(entity.getRoleDesc()),SysRole::getRoleDesc,entity.getRoleDesc());

    }

    private LambdaQueryWrapper<SysRole> queryByOr(SysRole entity){
        return new LambdaQueryWrapper<SysRole>()
                .eq(entity.getId()!=null,SysRole::getId,entity.getId())
                .or()
                .eq(StringUtils.hasText(entity.getRoleName()),SysRole::getRoleName,entity.getRoleName())
                .or()
                .eq(StringUtils.hasText(entity.getRoleCode()), SysRole::getRoleCode,entity.getRoleCode())
                .or()
                .eq(StringUtils.hasText(entity.getRoleDesc()), SysRole::getRoleDesc,entity.getRoleDesc());

    }

    public SysRole findOneByAnd(SysRole entity) {
        return sysRoleMapper.selectOne( queryByAnd(entity) );
    }
    public List<SysRole> findByAnd(SysRole entity) {
        return sysRoleMapper.selectList( queryByAnd(entity) );
    }

    public SysRole findOneByOr(SysRole entity) {
        return sysRoleMapper.selectOne( queryByOr(entity) );
    }
    public List<SysRole> findByOr(SysRole entity) {
        return sysRoleMapper.selectList( queryByOr(entity) );
    }

    public IPage<SysRole> page(SysRole search, int currentPage, int Pagesize,String sortField,String sortOrder) {
        Page<SysRole> page = new Page<>(currentPage , Pagesize);
        OrderItem orderItem = "asc".equalsIgnoreCase(sortOrder)?OrderItem.asc(sortField):OrderItem.desc(sortField);
        List<OrderItem> orders = Stream.of( orderItem ).collect(Collectors.toList());
        page.setOrders(orders);
        return sysRoleMapper.selectPage( page, queryByOr(search) );
    }
//
//    @Transactional
//    public Result create(SysRole entity) {
//        SysRole repoEntity = sysRoleRepository.findByRoleCode(entity.getRoleCode());
//        if(repoEntity!=null) return Result.error("角色名已存在！！！");
//        SysRole returnEntity=sysRoleRepository.save(entity);
//        if(returnEntity==null) return Result.error("新建角色失败！！！");
//        return Result.success("success");
//    }
//    @Transactional
//    public Result edit(SysRole entity) {
//        SysRole repoEntity = sysRoleRepository.getOne(entity.getRoleId());
//        if(repoEntity==null) return Result.error("角色不存在！！！");
//        entity = BeanUtil.copyNullProperties(entity,repoEntity);
//        SysRole returnEntity=sysRoleRepository.save(entity);
//        if(returnEntity==null) return Result.error("角色不存在！！！");
//        return Result.success("success");
//    }
//    @Transactional
//    public Result deleteByIds(List<Number> ids) {
//        ids.removeAll(Collections.singleton(null));
//        if(CollectionUtils.isEmpty(ids)) return Result.error("error");
//        List<Long> list=ids.stream().map(id-> Long.valueOf(String.valueOf(id ))).collect(Collectors.toList());
//        sysRoleRepository.deleteAll( sysRoleRepository.findAllById(list) );
//        return Result.success("success");
//    }
//    @Transactional
//    public Result assignResource(Number roleId , List<Number> resourceIds) {
//        resourceIds.removeAll(Collections.singleton(null));
//        StringBuilder getResourceIdsSqlWhere = new StringBuilder(" in ( ");
//        resourceIds.forEach(resourceId->{
//            getResourceIdsSqlWhere.append(resourceId+", ");
//        });
//        getResourceIdsSqlWhere.deleteCharAt(getResourceIdsSqlWhere.lastIndexOf(","));
//        getResourceIdsSqlWhere.append(" ) ");
//        String getResourceIdsSql = "WITH RECURSIVE temp AS " +
//                " ( " +
//                "   SELECT * FROM sys_resource r WHERE r.resource_id  "+getResourceIdsSqlWhere.toString() +
//                "   UNION ALL" +
//                "   SELECT r.* FROM sys_resource r,temp t WHERE t.parent_id = r.resource_id" +
//                " ) select resource_id from temp";
//        Query getResourceIdsQuery = entityManager.createNativeQuery(getResourceIdsSql);
//        List getResourceIds= getResourceIdsQuery.getResultList();
//        Set ids = new HashSet<>();
//        for (Object obj :getResourceIds) {
//            long id = Long.valueOf(String.valueOf(obj));
//            ids.add( id );
//        }
//        String deleteSql = "delete from sys_role_resource where role_id="+ roleId;
//        String insertSql = "insert into sys_role_resource (role_id,resource_id) select "+roleId+" as 'role_id',resource_id from sys_resource ";
//        StringBuilder insertSqlWhere = new StringBuilder(" where resource_id in ( ");
//        ids.forEach(resourceId->{
//            insertSqlWhere.append(resourceId+", ");
//        });
//        insertSqlWhere.deleteCharAt(insertSqlWhere.lastIndexOf(","));
//        insertSql += insertSqlWhere.toString()+" ) ";
//        Query deleteQuery = entityManager.createNativeQuery(deleteSql);
//        Query insertQuery = entityManager.createNativeQuery(insertSql);
//        int deleteResult= deleteQuery.executeUpdate();
//        int insertResult= insertQuery.executeUpdate();
//        return Result.success("成功！！！！");
//    }

}
